<template>
  <div class="fs-swipe-item" :class="itemTransition" :style="selfSetLeftStyle">
    <slot />
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, type CSSProperties, type Ref } from "vue";
import { SWIPE_KEY } from "./FsSwipe.vue";
import { useParent } from "./useRelation";
import type { ComponentInstance, SwipeProvide } from "./type";

const props = withDefaults(
  defineProps<{
    width: string;
    isTran: boolean;
    isScale: boolean;
  }>(),
  {
    width: "80vw",
  }
);

const init = (): {
  key: Ref<number>;
  fsSwipe: ComponentInstance;
} => {
  const { index: key, parent } = useParent<SwipeProvide>(SWIPE_KEY);
  const { fsSwipe }: SwipeProvide = parent;
  return {
    key,
    fsSwipe,
  };
};

const setStyle = (fsSwipe: ComponentInstance, key: Ref<number>) => {
  const currentIndex = computed(() => fsSwipe.swipe.syncIndex),
    childLen = computed(() => fsSwipe.childLength),
    // item过渡样式：scale改变
    itemTransition = computed(() => {
      const { isTouch } = fsSwipe.touch;
      return {
        "fs-swipe-item__transition": !isTouch,
        "fs-swipe-item__active": props.isTran && key.value === currentIndex.value,
        "fs-swipe-item__scale": props.isScale,
      };
    });

  // 无缝轮播设置左右边界left位移，默认left为0
  /**
   * 第一张图片展示时，左侧则放置最后两张图片
   * 最后一张图片展示时：右侧则放置前两张图片
   */
  const swipeTran = () => {
    const index = fsSwipe.swipe.index,
      { width } = fsSwipe.track;
    if (index === 0 && [childLen.value - 1, childLen.value - 2].includes(key.value)) {
      return -width;
    } else if (index === childLen.value - 1 && [0, 1].includes(key.value)) {
      return width;
    } else {
      return 0;
    }
  };

  return {
    swipeTran,
    itemTransition,
  };
};

const { key, fsSwipe } = init(),
  { itemTransition, swipeTran } = setStyle(fsSwipe, key);

const selfSetLeftStyle = computed(() => {
  const left = swipeTran();
  return {
    left: `${left}px`,
  } as CSSProperties;
});
</script>

<style scoped lang="scss">
.fs-swipe-item {
  display: inline-block;
  position: relative;
  height: 100%;
  width: v-bind("props.width");

  &__scale {
    transform: scale(0.9) translateY(2%);
  }
  &__active {
    transform: scale(1);
  }
  &__transition {
    transition: transform 0.25s;
  }
}
</style>
